<script setup lang="ts">
const { email, auth } = useAuth();
const frm = reactive({ password: "", new_password: "", re_password: "" });

const { msg, toast } = useStatus();
const { $post } = use$fetch();

const handleSubmit = async () => {
  if (frm.password === frm.new_password) {
    toast.value = "玩呢？新密码和现用密码一样";
    return;
  }
  if (frm.re_password !== frm.new_password) {
    toast.value = "两次输入的密码不一样";
    return;
  }
  if (frm.new_password.length < 6) {
    toast.value = "新密码至少6个字符";
    return;
  }

  await $post<AffResp>("/user/change-pwd", { ...frm }, (v) => {
    auth.value = null;
    msg.value = "密码修改成功，请重新登录";
    navigateTo("/auth/user-login");
    return v;
  });
};
</script>

<template>
  <FrontendPageTitle>账号信息</FrontendPageTitle>

  <form
    autocomplete="off"
    class="my-6 px-3 flex flex-col gap-y-4"
    @submit.prevent="handleSubmit"
  >
    <label class="grid grid-cols-12 items-center">
      <div class="col-span-4 lg:col-span-1">邮箱：</div>
      <div class="col-span-8 lg:col-span-11">{{ email }}</div>
    </label>

    <label class="grid grid-cols-12 items-center">
      <div class="col-span-4 lg:col-span-1">现用密码：</div>
      <div class="col-span-8 lg:col-span-11">
        <input
          class="bg-transparent outline-none border rounded px-3 py-1.5 block w-5/4 lg:w-1/4"
          required
          type="password"
          v-model="frm.password"
        />
      </div>
    </label>

    <label class="grid grid-cols-12 items-center">
      <div class="col-span-4 lg:col-span-1">新密码：</div>
      <div class="col-span-8 lg:col-span-11">
        <input
          class="bg-transparent outline-none border rounded px-3 py-1.5 block w-5/4 lg:w-1/4"
          required
          type="password"
          v-model="frm.new_password"
        />
      </div>
    </label>

    <label class="grid grid-cols-12 items-center">
      <div class="col-span-4 lg:col-span-1">重复密码：</div>
      <div class="col-span-8 lg:col-span-11">
        <input
          class="bg-transparent outline-none border rounded px-3 py-1.5 block w-5/4 lg:w-1/4"
          required
          type="password"
          v-model="frm.re_password"
        />
      </div>
    </label>

    <div class="grid grid-cols-12 items-center">
      <div class="col-span-4 lg:col-span-1"></div>
      <div
        class="col-span-8 lg:col-span-11 flex justify-start items-center gap-x-2"
      >
        <button
          type="submit"
          class="bg-cyan-600 text-white border rounded px-3 py-1.5"
        >
          提交
        </button>
        <button type="reset" class="bg-gray-300 border rounded px-3 py-1.5">
          重置
        </button>
      </div>
    </div>
  </form>
</template>
